/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package servlets.admin;

import dao.CategoryJpaController;
import dao.ColorsJpaController;
import dao.ImagesJpaController;
import dao.ProductJpaController;
import dao.SizesJpaController;
import java.io.IOException;
import java.io.*;
import java.util.*;
import javax.persistence.Persistence;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import pojo.Category;
import pojo.Colors;
import pojo.Images;
import pojo.Product;
import pojo.Sizes;
import services.ServiceAdminProducts;

/**
 *
 * @author Dell
 */
public class myUpload extends HttpServlet {

    int product_just_id;
    
    CategoryJpaController cc = new CategoryJpaController(Persistence.createEntityManagerFactory("ServletProjectPU"));
    ProductJpaController pc = new ProductJpaController(Persistence.createEntityManagerFactory("ServletProjectPU"));
    
    ImagesJpaController ic = new ImagesJpaController(Persistence.createEntityManagerFactory("ServletProjectPU"));
    ColorsJpaController colc = new ColorsJpaController(Persistence.createEntityManagerFactory("ServletProjectPU"));
    SizesJpaController sc = new SizesJpaController(Persistence.createEntityManagerFactory("ServletProjectPU"));
    
    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
       
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
      
        String fileName = null;
        
        Category c = new Category();
        Product p = new Product();
        List <Sizes> sizelist = new ArrayList();
        List <Colors> colorlist = new ArrayList();
        List <Images> imglist = new ArrayList();
        
        
        java.io.PrintWriter out = response.getWriter( );
        
   File file ;
   int maxFileSize = 5000 * 1024;
   int maxMemSize = 5000 * 1024;
   String filePath = getServletContext().getRealPath("product_images").toString()+"\\";
   String path = filePath.replace("build\\", "");
  
    
   
   // Verify the content type
   String contentType = request.getContentType();
   if ((contentType.indexOf("multipart/form-data") >= 0)) {

      DiskFileItemFactory factory = new DiskFileItemFactory();
      // maximum size that will be stored in memory
      factory.setSizeThreshold(maxMemSize);
      // Location to save data that is larger than maxMemSize.
      factory.setRepository(new File("c:\\temp"));

      // Create a new file upload handler
      ServletFileUpload upload = new ServletFileUpload(factory);
      // maximum file size to be uploaded.
      upload.setSizeMax( maxFileSize );
      try{ 
         // Parse the request to get file items.
         List fileItems = upload.parseRequest(request);

         List fileItems2 = fileItems;
         // Process the uploaded file items
         Iterator i = fileItems.iterator();

         out.println("<html>");
         out.println("<head>");
         out.println("<title>JSP File upload</title>");  
         out.println("</head>");
         out.println("<body>");
         while ( i.hasNext () ) 
         {
            FileItem fi = (FileItem)i.next();
          
           if (fi.isFormField())	
            {
                
                
                if(fi.getFieldName().equals("category"))
                {
                    c = cc.findCategory(new Integer(fi.getString()));
                    
                    p.setCategoryId(c);
                }
                else if(fi.getFieldName().equals("name"))
                {
                    p.setName(fi.getString());
                }
                else if(fi.getFieldName().equals("price"))
                {
                    p.setPrice(new Integer(fi.getString()));
                }
                else if(fi.getFieldName().equals("amount"))
                {
                    p.setAmount(new Integer(fi.getString()));
                }
                else if(fi.getFieldName().equals("brand"))
                {
                    p.setBrand(fi.getString());
                }
                else if(fi.getFieldName().equals("desc"))
                {
                    p.setDescription(fi.getString());
                    
                    System.out.println("ok desc");
                }
                
            }
          
                
                
         }
         
         product_just_id = pc.create(p);
                 
         Product ppp = new Product();
         ppp.setId(product_just_id);
         
         // Parse the request to get file items.
         

         // Process the uploaded file items
         Iterator i2 = fileItems2.iterator();
         
          while ( i2.hasNext () ) 
         {
            FileItem fi = (FileItem)i2.next();
            if ( !fi.isFormField () )	
            {
            // Get the uploaded file parameters
            String fieldName = fi.getFieldName();
            fileName = product_just_id+"_"+fi.getName();
            boolean isInMemory = fi.isInMemory();
            long sizeInBytes = fi.getSize();
            // Write the file
            if( fileName.lastIndexOf("\\") >= 0 ){
            file = new File( path + 
            fileName.substring( fileName.lastIndexOf("\\"))) ;
            }else{
            file = new File( path + 
            fileName.substring(fileName.lastIndexOf("\\")+1)) ;
            }
            fi.write( file ) ;
            out.println("Uploaded Filename: " + path + 
            fileName + "<br>");
            
            }
            else{
                ////////Sizes + Colors///////////////
                 if(fi.getFieldName().equals("size1"))
                {
                    Sizes small = new Sizes();
                    small.setProductId(ppp);
                    small.setSize(fi.getString());
                    sc.create(small);
                }
                else if(fi.getFieldName().equals("size2"))
                {
                    Sizes medium = new Sizes();
                    medium.setProductId(ppp);
                    medium.setSize(fi.getString());
                    sc.create(medium);
                    
                }
                else if(fi.getFieldName().equals("size3"))
                {
                    Sizes large = new Sizes();
                    large.setProductId(ppp);
                    large.setSize(fi.getString());
                    sc.create(large);
                }
                else if(fi.getFieldName().equals("color"))
                {
                    StringTokenizer st = new StringTokenizer(fi.getString(), ",");
                    while(st.hasMoreElements())
                    {
                        Colors col = new Colors();
                        col.setProductId(ppp);
                        col.setColor((String) st.nextElement());
                        colc.create(col);
                    }
                }
            }
            
         }
         
         
                    Images is = new Images();
                    is.setProductId(ppp);
                    is.setLocation("product_images/"+fileName);
                    ic.create(is);
         
                    response.sendRedirect("admin_viewProducts.jsp");
                    
         out.println("</body>");
         out.println("</html>");
      
         
         
         
         
      }catch(Exception ex) {
         System.out.println(ex);
      }
   }else{
      out.println("<html>");
      out.println("<head>");
      out.println("<title>Servlet upload</title>");  
      out.println("</head>");
      out.println("<body>");
      out.println("<p>Error</p>"); 
      out.println("</body>");
      out.println("</html>");
   }
        
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
